package com.jlwl.houseservice.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jlwl.houseservice.common.JwtTokenUtil;
import com.jlwl.houseservice.entity.User;
import com.jlwl.houseservice.mapper.UserMapper;
import com.jlwl.houseservice.service.UserService;
import com.jlwl.houseservice.vo.LoginResultVO;
import com.jlwl.houseservice.vo.UserLoginVO;
import com.jlwl.houseservice.vo.UserRegisterVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.Objects;

/**
 * 用户Service实现类
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    @Transactional
    public LoginResultVO register(UserRegisterVO userRegisterVO) {
        // 验证两次密码是否一致
        if (!Objects.equals(userRegisterVO.getPassword(), userRegisterVO.getConfirmPassword())) {
            throw new RuntimeException("两次密码不一致");
        }

        // 检查手机号是否已注册
        User existUser = getOne(new LambdaQueryWrapper<User>()
                .eq(User::getPhone, userRegisterVO.getPhone()));
        if (existUser != null) {
            throw new RuntimeException("该手机号已注册");
        }

        // 检查用户名是否已存在
        existUser = getOne(new LambdaQueryWrapper<User>()
                .eq(User::getUsername, userRegisterVO.getUsername()));
        if (existUser != null) {
            throw new RuntimeException("该用户名已存在");
        }

        // 创建新用户
        User user = new User();
        user.setUsername(userRegisterVO.getUsername());
        user.setPassword(passwordEncoder.encode(userRegisterVO.getPassword()));
        user.setPhone(userRegisterVO.getPhone());
        user.setRealName(userRegisterVO.getRealName());
        user.setGender(userRegisterVO.getGender());
        user.setBalance(new BigDecimal("0"));
        user.setStatus(1); // 正常状态
        user.setLastLoginTime(LocalDateTime.now());
        user.setCreatedAt(LocalDateTime.now());
        user.setUpdatedAt(LocalDateTime.now());

        // 保存用户
        save(user);

        // 生成JWT令牌
        UserDetails userDetails = org.springframework.security.core.userdetails.User
                .withUsername(user.getPhone())
                .password(user.getPassword())
                .authorities("ROLE_USER")
                .build();
        String token = jwtTokenUtil.generateToken(userDetails);

        // 构建返回结果
        LoginResultVO loginResultVO = new LoginResultVO();
        loginResultVO.setId(user.getId());
        loginResultVO.setUsername(user.getUsername());
        loginResultVO.setRealName(user.getRealName());
        loginResultVO.setAvatar(user.getAvatar());
        loginResultVO.setRole("ROLE_USER");
        loginResultVO.setToken(token);
        loginResultVO.setLastLoginTime(user.getLastLoginTime());

        return loginResultVO;
    }

    @Override
    public LoginResultVO login(UserLoginVO userLoginVO) {
        // 根据手机号查询用户
        User user = getOne(new LambdaQueryWrapper<User>()
                .eq(User::getPhone, userLoginVO.getPhone()));
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }

        // 进行身份验证
        Authentication authentication = authenticationManager.authenticate(
                new UsernamePasswordAuthenticationToken(
                        userLoginVO.getPhone(),
                        userLoginVO.getPassword()
                )
        );

        // 设置认证信息
        SecurityContextHolder.getContext().setAuthentication(authentication);

        // 生成JWT令牌
        UserDetails userDetails = (UserDetails) authentication.getPrincipal();
        String token = jwtTokenUtil.generateToken(userDetails);

        // 更新用户最后登录时间
        user.setLastLoginTime(LocalDateTime.now());
        updateById(user);

        // 构建返回结果
        LoginResultVO loginResultVO = new LoginResultVO();
        loginResultVO.setId(user.getId());
        loginResultVO.setUsername(user.getUsername());
        loginResultVO.setRealName(user.getRealName());
        loginResultVO.setAvatar(user.getAvatar());
        loginResultVO.setRole("ROLE_USER");
        loginResultVO.setToken(token);
        loginResultVO.setLastLoginTime(user.getLastLoginTime());

        return loginResultVO;
    }

    @Override
    public User getUserInfo(Integer userId) {
        User user = getById(userId);
        if (user != null) {
            // 清除敏感信息
            user.setPassword(null);
        }
        return user;
    }

    @Override
    public boolean updateUserInfo(User user) {
        User existUser = getById(user.getId());
        if (existUser == null) {
            return false;
        }

        // 只允许更新部分字段
        User updateUser = new User();
        updateUser.setId(user.getId());
        updateUser.setUsername(user.getUsername());
        updateUser.setRealName(user.getRealName());
        updateUser.setGender(user.getGender());
        updateUser.setAvatar(user.getAvatar());
        updateUser.setUpdatedAt(LocalDateTime.now());

        return updateById(updateUser);
    }
} 